package com.hsyt.pfc.support.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @Description: traceId工具类
 * @ClassName: TraceIdUtil
 * @Package: com.yuntai.medicalpop.framework.support.util
 * @Author: wangze@hsyuntai.com
 * @Date: 2018/5/29 13:17
 * @Copyright: 版权归 HSYUNTAI 所有
 */
public class TraceIdUtil {

    private static ThreadLocal<String> localTraceId = new ThreadLocal<>();

    private TraceIdUtil() {
    }

    /**
     * @Description: 获取traceId
     * @Param:
     * @Return:
     * @Author: wangze@hsyuntai.com
     * @Date: 2018/5/29 13:23
     */
    public static String getLocalTraceId() {
        return localTraceId.get();
    }

    /**
     * @Description: 给线程变量设置traceId
     * @Param:
     * @Return:
     * @Author: wangze@hsyuntai.com
     * @Date: 2018/5/29 13:24
     */
    public static void createLocalTraceId() {
        if(StringUtils.isEmpty(localTraceId.get())) {
            setLocalTraceId(getUUID());
        }
    }

    /**
     * @Description: 给线程变量设置traceId
     * @Param:
     * @Return:
     * @Author: wangze@hsyuntai.com
     * @Date: 2018/5/29 13:25
     */
    public static void setLocalTraceId(String traceId) {
        localTraceId.set(traceId);
    }

    /**
     * @Description: 清楚线程变量中的treaceId
     * @Param:
     * @Return:
     * @Author: wangze@hsyuntai.com
     * @Date: 2018/5/29 13:25
     */
    public static void clearLocalTraceId(){
        localTraceId.remove();
    }

    /**
     * @Description: 获取UUID
     * @Param:
     * @Return:
     * @Author: wangze@hsyuntai.com
     * @Date: 2018/5/29 13:26
     */
    public static String getUUID() {
        return DateUtil.formateDate(new Date(), DateUtil.FORMAT_yyyyMMddHH) + UUID.randomUUID().toString().replace("-", "");
    }

}
